package com.ddw.wotcg.server.utils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public abstract class RequestHelper {
	
	public static final String SESSION_COOKIE = "session";
	private static final Map<String, String> EMPTY_COOKIES = Collections
			.unmodifiableMap(new HashMap<String, String>(0));
	
	public static UUID getSession(Map<String, String> cookies) {
		// Check we have a session id
		final String sessionId = cookies.get(SESSION_COOKIE);
		if (sessionId == null || sessionId.isEmpty()) {
			return null;
		}
		
		// Check it is in the right format
		try {
			return UUID.fromString(sessionId);
		} catch (final IllegalArgumentException e) {
			return null;
		}
	}
	
	public static Map<String, String> parseCookies(HttpServletRequest request) {
		final Cookie[] array = request.getCookies();
		if (array == null) {
			return EMPTY_COOKIES;
		}
		
		final Map<String, String> cookies = new HashMap<String, String>();
		Cookie cookie;
		for (int i = 0, s = array.length; i < s; i++) {
			cookie = array[i];
			cookies.put(cookie.getName(), cookie.getValue());
		}
		return cookies;
	}
	
}
